package uscdb.service;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import uscdb.model.Tlogic;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml" })
public class NewSearch {

	@Autowired
	private SessionFactory sessionFactory;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Test
	public void test() {
		List<Tlogic> tlogicList = new ArrayList<Tlogic>();
		String searchString = "vdvdsf";
		String product = "USCDB";
		String version = "PaaS";

		Session session = sessionFactory.openSession();
		FullTextSession fullTextSession = Search.getFullTextSession(session);
		QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Tlogic.class)
				.get();
		org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword()
				.onFields("content", "tlogicfile.tversion.name", "tlogicfile.tversion.tproduct.name")
				.ignoreFieldBridge().matching(searchString + " " + product + " " + version).createQuery();

		FullTextQuery ftquery = fullTextSession.createFullTextQuery(luceneQuery, Tlogic.class);

		ftquery.setFirstResult(0);
		ftquery.setMaxResults(10);
		// 返回 符合页码条数的记录
		tlogicList = ftquery.list();

		for (Tlogic t : tlogicList) {
			System.out.println(
					"逻辑名：" + t.getTitle() + "； 逻辑所属产品：" + t.getTlogicfile().getTversion().getTproduct().getName()
							+ "； 逻辑所属版本：" + t.getTlogicfile().getTversion().getName());
		}

	}

}
